package com.epi.web.redis;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.*;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author dxy
 * @version 1.0
 */
@Slf4j
public class JedisDemo {
    public static void main(String[] args) {
//        jedisClose();
//        scriptSha("1");
//        sentinelFailover();
        clusterBasic();
    }

    private static void clusterBasic() {
        Set<HostAndPort> jedisClusterNode = new HashSet<>();
        for (int i = 6379; i <= 6384; i++) {
            jedisClusterNode.add(new HostAndPort("127.0.0.1", i));
        }
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        JedisCluster jedisCluster = new JedisCluster(jedisClusterNode,1000,1000,5,poolConfig);
        jedisCluster.set("f","hello");
        String s = jedisCluster.get("e");
        System.out.println(s);
    }

    private static void sentinelFailover() {
        Jedis jedisSentinel = new Jedis("127.0.0.1", 26379);
        jedisSentinel.subscribe(new JedisPubSub() {
            @Override
            public void onMessage(String channel, String message) {
                log.info("Sentinel event received: [{}] {}", channel, message);
            }
        }, "+switch-master", "+sdown", "+odown", "-sdown", "+failover-state-select-slave");
    }

    private static void jedisClose() {
        JedisPool jedisPool = new JedisPool("localhost", 6379);
        try (
//             jedis.close 优先归还，直连下才关闭
            Jedis jedis = jedisPool.getResource();
        ) {
            LocalDateTime now = LocalDateTime.now();
            jedis.lpush("li", now.toString());
//             读取数据
            List<String> li = jedis.lrange("li", 0, -1);
            li.forEach(System.out::println);
        }
    }

    public static void mdel(List<String> keys) {
        Jedis jedis = new Jedis("localhost", 6379);
        Pipeline pipeline = jedis.pipelined();
        for (String key : keys) {
            pipeline.del(key);
        }
        pipeline.sync();
    }

    public static void scriptSha(String param) {
        Jedis jedis = new Jedis("localhost", 6379);
        String script = "return redis.call('get', 'N'..KEYS[1])";

        Object eval = jedis.eval(script, 1, param);
        System.out.println(eval);

        String scriptSha = jedis.scriptLoad(script);
        System.out.println(scriptSha);

        Object evalsha = jedis.evalsha(scriptSha, 1, param);
        System.out.println(evalsha);

    }
}
